//
//  ContactKeyboardViewController.m
//  HandyDialer
//
//	Developed by Team Synergy
//  Created by Jordan Tseng on 11/20/11.
//  Coders: Jacky Li and Jordan Tseng 
//  Graphic Designer: Derek Fong
//  Developers: Brad Lisson, Derek Fong, Jacky Li, Jeremy Gangoso, Jordan Tseng
//  Copyright HandyDialer 2011. All rights reserved.

#import "ContactKeyboardViewController.h"

@implementation ContactKeyboardViewController
@synthesize currentInput;
@synthesize highlightArea;
@synthesize backgroundArea;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
    {
        // Custom initialization
		rowCounter = 0;
		columnCounter = 0;
		iterationCounter = 0;
		buttonSelect = FALSE;
    }
    return self;
}



- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



#pragma mark - View lifecycle

- (void)viewDidLoad 
{
	DataStorage *data = [DataStorage sharedData];
	// hint for keyword if searching
	if (self.nibName == @"ContactSearchView")
	{
		currentInput.text = @"Please input keyword";
		currentInput.textColor = [UIColor redColor];
	}
	// hint for first name if adding contact
	else if (self.nibName == @"ContactAddNameView")
	{
		[data setCurrentContact:nil];
		currentInput.text = @"First Name";
		currentInput.textColor = [UIColor redColor];
	}
	// show current first name if editing
	else if (self.nibName == @"ContactEditNameView")
	{
		currentInput.text = ABRecordCopyValue([data getCurrentContact], kABPersonFirstNameProperty);
		currentInput.textColor = [UIColor darkGrayColor];
	}
	characterList = [NSArray arrayWithObjects:@"a", @"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o", @"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@".",@" ",@"-",@"z",nil];
	[characterList retain];
	defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_contacts_keyboard.png"]]];
	[super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated
{

	defaults = [NSUserDefaults standardUserDefaults];
	speed = [defaults floatForKey:@"Speed"];
	highlightColor = [defaults stringForKey:@"Highlight"];
	themeColor = [defaults stringForKey:@"Theme"];
    [backgroundArea setImage:[UIImage imageNamed: [themeColor stringByAppendingString:@"_contacts_keyboard.png"]]];
	
	if (uniTimer == nil && buttonSelect == FALSE)
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
	else if (uniTimer == nil && buttonSelect == TRUE)
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(buttonChange) userInfo:nil repeats:YES];
	[super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	if (uniTimer != nil)
	{
		[uniTimer invalidate];
		uniTimer = nil;
	}
	[super viewDidDisappear:animated];
}

- (void)dealloc 
{
	[characterList release];
	[firstName release];
	[backgroundArea release];
	[highlightArea release];
    [super dealloc];
}

// decides which row to highlight
- (void)highlightChange:(NSString *)picture
{
    UIImage *image = [UIImage imageNamed: picture];
    [highlightArea setImage:image];
	
}

// the process of appending input to current input
- (void)appendNum:(int)input
{
	currentInput.textColor = [UIColor blackColor];
	if (firstName == NULL)
	{
		firstName = [characterList objectAtIndex:input];
	}
	else
	{
		firstName = [firstName stringByAppendingString:[characterList objectAtIndex:input]];
	}
	firstName = [firstName capitalizedString];
	[firstName retain];
	currentInput.text = firstName;
	NSLog(@"%@",firstName);
	
}

- (void)returnToView:(NSString *)viewName:(UIViewController *)previousView
{
	// recursively look for view to return to
	previousView = [previousView presentingViewController];
	NSLog(@"%@", previousView.nibName);
	if (previousView.nibName == viewName)
	{
		[previousView dismissModalViewControllerAnimated:NO];
	}
	else
	{
		[self returnToView:(viewName):(previousView)];
	}
}

// Actually switching to that screen 
-(IBAction)switchView:(id)sender
{
	// Does nothing if rowCounter is 0
	if(rowCounter != 0)
	{
		// Checks to see if a button is being selected
		if(buttonSelect == true && columnCounter != 0)
		{
			// Stops timer and reset timeout counter
			[uniTimer invalidate];
			uniTimer = nil;
			iterationCounter = 0;
			
			// Special case for Row 6 to deal with confirm, backspace, clr and back
			if(rowCounter == 6)
			{
				switch (columnCounter)
				{
					//confirm
					case 1:
					{
						DataStorage *data = [DataStorage sharedData];
						buttonSelect = false;
						rowCounter = 0;
						columnCounter = 0;
						// search contact
						if (self.nibName == @"ContactSearchView")
						{
							if (firstName != nil)
							{

								//insert contact search results view initialization here
								
								[data setSearchName:firstName];
								ContactResultViewController *myViewController = [[ContactResultViewController alloc]
																			initWithNibName:@"ContactResultView"
																			bundle:nil];
								[self presentModalViewController:myViewController animated:NO];
								;
								[highlightArea setImage:nil];
							}
							// Displays invalid input screen if no firstName was entered
							else 
							{
								InvalidInputViewController *myViewController = [[InvalidInputViewController alloc]
																			initWithNibName:@"InvalidInputView"
																			bundle:nil];
								[self presentModalViewController:myViewController animated:NO];
								;
								[highlightArea setImage:nil];
							}
						}
						// add contact
						else if (self.nibName == @"ContactAddNameView")
						{
							if (firstName != nil)
							{
								// add first name to contact
								if (firstNameInputted == false)
								{
									firstNameInputted = true;
									ABRecordRef newContact = ABPersonCreate();
									ABRecordSetValue(newContact, kABPersonFirstNameProperty,firstName,nil);
									[data setCurrentContact:newContact];
									firstName = nil;
									currentInput.text = @"Last Name";
									currentInput.textColor = [UIColor redColor];
									[self rowChange];
									uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
								
								}
								// add last name to contact and go to number input screen
								else
								{
									ABRecordRef newContact = [data getCurrentContact];
									ABRecordSetValue(newContact,kABPersonLastNameProperty,firstName,nil);
									[data setCurrentContact:newContact];
									firstName = nil;
									currentInput.text = nil;
									ContactNumberViewController *myViewController = [[ContactNumberViewController alloc]
																					initWithNibName:@"ContactAddNumberView"
																					bundle:nil];
									[self presentModalViewController:myViewController animated:NO];
									[firstName release];
									[highlightArea setImage:nil];
								}
							}
							else
							{
								// invalid input if left blank
								InvalidInputViewController *myViewController = [[InvalidInputViewController alloc]
																				initWithNibName:@"InvalidInputView"
																				bundle:nil];
								[self presentModalViewController:myViewController animated:NO];
								;
								[highlightArea setImage:nil];
							}
						}
						// edit contact
						else if (self.nibName == @"ContactEditNameView")
						{	
							if (firstNameInputted == false)
							{	// if no new input, leave first name untouched
								if (firstName == nil)
								{
									firstNameInputted = true;
									currentInput.text = ABRecordCopyValue([data getCurrentContact],kABPersonLastNameProperty);
									[self rowChange];
									uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
								}
								// save new first name
								else
								{
									firstNameInputted = true;
									currentInput.text = ABRecordCopyValue([data getCurrentContact],kABPersonLastNameProperty);
									currentInput.textColor = [UIColor darkGrayColor];
									ABRecordRef editedContact = [data getCurrentContact];
									ABRecordSetValue(editedContact,kABPersonFirstNameProperty,firstName,nil);
									[data setCurrentContact:editedContact];
									firstName = nil;
									[self rowChange];
									uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
								}
							}
							else
							{
								// if no new input, leave last name untouched
								if (firstName == nil)
								{
									ContactNumberViewController *myViewController = [[ContactNumberViewController alloc]
																					 initWithNibName:@"ContactEditNumberView"
																					 bundle:nil];
									[self presentModalViewController:myViewController animated:NO];
									;
									[highlightArea setImage:nil];
								}
								// save new last name and ask for new number
								else
								{
									currentInput.text = nil;
									ABRecordRef editedContact = [data getCurrentContact];
									ABRecordSetValue(editedContact,kABPersonLastNameProperty,firstName,nil);
									[data setCurrentContact:editedContact];
									firstName = nil;
									ContactNumberViewController *myViewController = [[ContactNumberViewController alloc]
																					 initWithNibName:@"ContactEditNumberView"
																					 bundle:nil];
									[self presentModalViewController:myViewController animated:NO];
									;
									[firstName release];
									[highlightArea setImage:nil];
								}
							}
								
						}
						break;
					}
					// Backspace
					case 2:
						if([firstName length] == 1)
							firstName = NULL;
						else
							firstName = [firstName substringToIndex:[firstName length] - 1];
						currentInput.text = firstName;
						columnCounter = 0;
						rowCounter = 0;
						buttonSelect = false;
						[self rowChange];
						uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
						NSLog(@"%@",firstName);
						break;
                        
					// Clear
					case 3:
						firstName = NULL;
						currentInput.text =  firstName;
						columnCounter= 0;
						rowCounter = 0;
						buttonSelect = false;
						[self rowChange];
						uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
						NSLog(@"%@",firstName);
						break;
						
					// Back to contact card or contact menu
					case 4:
						if (self.nibName == @"ContactEditNameView")
						{
							DataStorage *data = [DataStorage sharedData];
							
							ABAddressBookRef tempBook = ABAddressBookCreate();
							[data setCurrentContact:ABAddressBookGetPersonWithRecordID(tempBook, ABRecordGetRecordID([data getCurrentContact]))];
							[self returnToView:@"ContactCardView":self];
							[firstName release];
						}
						else
						{
							[self returnToView:@"ContactView":self];
							[firstName release];
						}
						break;
				}
			}
			// Append input entered for non-special characters
			else
			{
				NSLog(@"%d",(columnCounter-1+(rowCounter-1)*6));
				[self appendNum:(columnCounter-1+(rowCounter-1)*6)];
				
				columnCounter = 0;
				rowCounter = 0;
				buttonSelect = false;
				[self rowChange];
				uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
			}
			
		}
		// Case for row select
		else
		{
			[uniTimer invalidate];
			uniTimer = nil;
			buttonSelect = true;
			columnCounter = 0;
			[self buttonChange];
			uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(buttonChange) userInfo:nil repeats:YES];
			
		}
	}
	
	
}

// Decides which row to go to
-(void)rowChange
{
    
	if( rowCounter == 6)
	{
		rowCounter = 0;
	}
	rowCounter += 1;
	NSString *next = highlightColor;
    next = [next stringByAppendingString: @"_contacts_keyboard_row"];  
	next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", rowCounter]];
	next = [next stringByAppendingString:@".png"];
	[self highlightChange:next];
    
    
}

// decides which button should be displayed next
-(void)buttonChange 
{
    
    
	if (rowCounter == 6)
	{
		if (columnCounter == 4)
		{
			columnCounter = 0;
			iterationCounter += 1;
		}
	}
	if (rowCounter == 5)
	{
		if (columnCounter == 5)
		{
			columnCounter = 0;
			iterationCounter += 1;
		}
	}
	else
	{
		if (columnCounter == 6)
		{
			columnCounter = 0;
			iterationCounter += 1;
		}
	}
	if(iterationCounter == 3)
	{
		[uniTimer invalidate];
		uniTimer = nil;
		iterationCounter = 0;
		columnCounter = 0;
		rowCounter = 0;
		buttonSelect = false;
		[self rowChange];
		uniTimer = [NSTimer scheduledTimerWithTimeInterval:(speed) target:self selector:@selector(rowChange) userInfo:nil repeats:YES];
		
	}
	else
	{
		columnCounter += 1;
		NSString *next = highlightColor;
		next = [next stringByAppendingString:@"_contacts_keyboard_"];  
		next = [next stringByAppendingString:[NSString stringWithFormat:@"%d", columnCounter+(rowCounter-1)*6]];
		next = [next stringByAppendingString:@".png"];
		[self highlightChange:next];
	}
    
}
@end
